<?php

namespace Home\Controller;

use Home\Controller\BaseController;

class PublicController extends BaseController {

    public function _initialize() {
        
    }

    //用户登录
    public function login() {
        $strPhone = I("phone");
        $strPwd = I('password');
        if (empty($strPhone)) {
            $this->ajaxReturn(0, "请输入手机号");
        }
        empty($strPhone) && $this->ajaxReturn(0, "请输入手机号");
        empty($strPwd) && $this->ajaxReturn(0, "请输入密码");

        //$objUser = M('Users');
        $userInfo = M()->field("u.user_id,u.nick_name,u.face,u.real_name,u.phone,u.create_time,u.account_status,u.user_status,u.company,u.position,u.channel,u.company_address,u.refuse_desc,u.refuse_time,is_perfect")
                        ->table("ot_users as u ")
                        ->where(array('u.phone' => $strPhone, 'u.password' => md5($strPwd)))->find();
        empty($userInfo) && $this->error('登录失败，用户名或密码错误');

        if ($userInfo['face']) {
            $userInfo['face'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $userInfo['face'];
        }

        $content = \Common\Util\Util::randStr(60, 2) . $userInfo['phone'] . NOW_TIME . '123456';
        $userToken = \Common\Util\Util::encrypt($content);
        $expireTime = 30;
        $expireTime = time() + ($expireTime ? $expireTime : 30) * 24 * 3600;
        $ut['user_token'] = $userToken;
        $userInfo['user_token'] = $userToken;
        //保存user_token
        $res = M('Users')->where(['user_id' => $userInfo['user_id']])->save($ut);
        M('LogLogin')->add(['user_id'=>$userInfo['user_id']]);
        unset($userInfo['user_id']);

        $this->success("登录成功", $userInfo);
    }

    public function wxlogin() {
        $openid = I("wx_openid");

        if (empty($openid)) {
            $this->error('请传入微信openid');
        }

        $where['u.wx_openid'] = $openid;

        $userInfo = M()->field("u.user_id,u.nick_name,u.face,u.real_name,u.phone,u.create_time,u.account_status,u.user_status,u.company,u.position,u.channel,u.company_address,u.refuse_desc,u.refuse_time,is_perfect")
                        ->table("ot_users as u ")
                        ->where($where)->find();

        if (!empty($userInfo)) {
            $content = \Common\Util\Util::randStr(60, 2) . $userInfo['phone'] . NOW_TIME . '123456';
            $userToken = \Common\Util\Util::encrypt($content);
            $expireTime = 30;
            $expireTime = time() + ($expireTime ? $expireTime : 30) * 24 * 3600;
            $ut['user_token'] = $userToken;
            $userInfo['user_token'] = $userToken;
            //保存user_token
            $res = M('Users')->where(['user_id' => $userInfo['user_id']])->save($ut);
            $userInfo['face'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $userInfo['face'];
             M('LogLogin')->add(['user_id'=>$userInfo['user_id']]);
            unset($userInfo['user_id']);
        }

        $this->success("登录成功", $userInfo);
    }

    //验证码发送
    public function sendCode() {
        $strPhone = I('phone');
        $type = I('type', 1, 'intval');
        empty($strPhone) && $this->error("请输入手机号");

        $objUser = M('Users');
        $userInfo = $objUser->where(array('phone' => $strPhone))->find();

        //1(注册)，2（找回密码）
        if ($type == 1) {
            //验证手机号是否存在
            if (!empty($userInfo) && $userInfo['user_status'] != 2) {
                $this->error("该手机号已被注册");
                return;
            }
        }
        if ($type == 2) {
            //验证手机号是否不存在
            if (empty($userInfo)) {
                $this->error("该手机未注册");
                return;
            }
        }

        $strRand = createVerify($strPhone);
//        if ($strRand) {
//            $this->success("发送成功");
//        } else {
//            $this->error('发送失败');
//        }

        $this->success("发送成功");

        //测试使用
//        S($strPhone, '1234', 3600);
    }

    public function bindPhone() {
        $strPhone = I('phone');
        $openid = I("wx_openid");
        $strCode = I('code');
        $strCode != S($strPhone) && $this->error("验证码错误");

        if (empty($openid)) {
            $this->error("请传入微信openid");
        }

        //$objUser = M('Users');
        $userInfo = M()->field("u.user_id,u.nick_name,u.face,u.real_name,u.phone,u.create_time,u.account_status,u.user_status,u.company,u.position,u.channel,u.company_address,u.refuse_desc,u.refuse_time,is_perfect")
                        ->table("ot_users as u ")
                        ->where(array('u.phone' => $strPhone))->find();

        if (empty($userInfo)) {
            $this->error('该手机号还未注册');
        }


        $content = \Common\Util\Util::randStr(60, 2) . $userInfo['phone'] . NOW_TIME . '123456';
        $userToken = \Common\Util\Util::encrypt($content);
        $expireTime = 30;
        $expireTime = time() + ($expireTime ? $expireTime : 30) * 24 * 3600;
//        //生成user_token数据
//        $user_id = $data['user_id'];

        $ut['user_token'] = $userToken;
        $ut['wx_openid'] = $openid;
        //保存user_token
        $res = M('Users')->where(['user_id' => $userInfo['user_id']])->save($ut);

        $userInfo = M()->field("u.user_id,u.nick_name,u.face,u.real_name,u.phone,u.create_time,u.account_status,u.user_status,u.company,u.position,u.channel,u.company_address,u.refuse_desc,u.refuse_time,is_perfect")
                        ->table("ot_users as u ")
                        ->where(['user_id' => $userInfo['user_id']])->find();

        $userInfo['user_token'] = $userToken;
        unset($userInfo['user_id']);

        $this->success('绑定成功', $userInfo);
    }

    public function checkVcode() {
        $strPhone = I('phone');
        $strCode = I('code');
        $strCode != S($strPhone) && $this->error("验证码错误");
        $this->success('通过验证');
    }

    //注册
    public function register() {
        $strPhone = I('phone');
        $strPwd = I('password');
//        $strCode = I('code');
        $realName = I('real_name');
        $company = I('company');
        $channel = I('channel');
        $position = I('position');
        $company_address = I('company_address');
        $openid = I("wx_openid");

        $is_re_apply = I('is_re_apply', 0, 'intval');
        if ($is_re_apply == 0) {
            empty($strPhone) && $this->error("请输入手机号");
            empty($strPwd) && $this->error("请输入密码");
            $data['phone'] = $strPhone;
            $data['password'] = md5($strPwd);
//            $strCode != S($strPhone) && $this->error("验证码错误");
        } else {
            $userTokenInfo = $this->isLogin();
            $this->user_id = $userTokenInfo['userId'];
        }
        empty($realName) && $this->error("请输入真实姓名");
        empty($company) && $this->error("请输入公司名");
        empty($position) && $this->error("请输入职位");
        empty($channel) && $this->error("请输入渠道");
        empty($company_address) && $this->error("请输入公司地址");


        $data['real_name'] = $realName;
        $data['company'] = $company;
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['account_status'] = 0;
        $data['user_status'] = 0;
        $data['wx_openid'] = $openid;
        $data['company'] = $company;
        $data['position'] = $position;
        $data['channel'] = $channel;
        $data['company_address'] = $company_address;


        if ($is_re_apply == 0) {
            $exist_phone_where['phone'] = $strPhone;
        } else {
            $exist_phone_where['user_id'] = $this->user_id;
        }

        $objUser = M("Users");
        $exist_phone = $objUser->where($exist_phone_where)->find();

        $user_id = 0;
        //被拒绝用户重新注册则修改状态为待审核
        if (!empty($exist_phone)) {
            if ($exist_phone['user_status'] == 2) {
                $data['user_id'] = $exist_phone['user_id'];
                $objUser->save($data);
            } else {
                $this->error("手机号已被注册");
            }
        } else {
            $user_id = $objUser->add($data);
            $data['user_id'] = $user_id;
        }


        unset($data['password']);
        unset($data['create_time']);

        if ($is_re_apply == 0) {
            /*             * ****token 开始********************************** */
            //$salt = hash('md5', \Common\Util\Util::randStr(20, 2).$data['phone']);
            $content = \Common\Util\Util::randStr(60, 2) . $data['phone'] . NOW_TIME . '123456';
            $userToken = \Common\Util\Util::encrypt($content);
            $expireTime = 30;
            $expireTime = time() + ($expireTime ? $expireTime : 30) * 24 * 3600;
//        //生成user_token数据
//        $user_id = $data['user_id'];

            $ut['user_token'] = $userToken;
            //保存user_token
            $res = M('Users')->where(['user_id' => $user_id])->save($ut);

            $userInfo = M()->field("u.user_id,u.nick_name,u.face,u.real_name,u.phone,u.create_time,u.account_status,u.user_status,u.company,u.position,u.channel,u.company_address,u.refuse_desc,u.refuse_time,is_perfect")
                            ->table("ot_users as u ")
                            ->where(['user_id' => $user_id])->find();

            $userInfo['user_token'] = $userToken;
            unset($userInfo['user_id']);
        } else {
            $userInfo['user_token'] = I('user_token');
        }
        /*         * ****token结束******************************************* */
        $this->success('注册成功', $userInfo);
    }

    //忘记密码修改
    public function forgetPwd() {
        $strPhone = I('phone');
        $strPwd = I('password');
        $strCode = I('code', -1);
        empty($strPhone) && $this->ajaxReturn(0, "请输入手机号");
        empty($strPwd) && $this->ajaxReturn(0, "请输入密码");
        $strCode != S($strPhone) && $this->ajaxReturn(0, "验证码错误");

        $data['password'] = md5($strPwd);
        $res = M("Users")->where(array('phone' => $strPhone))->save($data);

        if ($res) {
            $this->success();
        } else {
            $this->ajaxReturn(0, '修改失败');
        }
    }

    //退出
    public function logout() {
        $param = I('user_token');

        $where['user_token'] = $param;
        $userInfo = M()->field("u.user_id,u.user_token,u.phone")
                        ->table("ot_users as u ")
                        ->where($where)->find();

        if (!empty($userInfo)) {
            $res = M('Users')->where(array('user_id' => $userInfo['user_id']))->save(['user_token' => '']);
        }
        $this->success('退出成功');
    }

    public function getAdList() {
        $where['start_time'] = array('ELT', date('Y-m-d H:i:s', time()));
        $where['end_time'] = array('EGT', date('Y-m-d H:i:s', time()));
//        $where['postion_id'] = 1;
        $ad_list = M("Ad")->field('ad_id,img_url,title,to,type')->where($where)->select();

        if ($ad_list) {
            foreach ($ad_list as &$val) {
                $val['img_url'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['img_url'];
            }

            unset($val);
        } else {
            $ad_list = [];
        }
        $this->success('获取成功', $ad_list);
    }

    public function getCateList() {

        $pid = I('pid', 0, 'intval');

        if ($pid != 0) {
            $where['cate_id'] = $pid;
//            $cateList = M('GoodsCate')->field('cate_id,title,pid')->where(['cate_id' => $pid])->find();
//            if (!empty($cateList)) {
//                $cate_son = M('GoodsCate')->field('cate_id,title,pid')->where(['pid' => $cateList['cate_id']])->order('sort')->select();
//                if ($cate_son) {
//                    $cateList['cate_son'] = $cate_son;
//                } else {
//                    $cateList['cate_son'] = [];
//                }
//            }
        } else {
            $where['pid'] = $pid;
//            $cateList = M('GoodsCate')->field('cate_id,title,pid')->where(['pid' => $pid])->order('sort')->select();
//            if (!empty($cateList)) {
//                foreach ($cateList as &$val) {
//                    $cate_son = M('GoodsCate')->field('cate_id,title,pid')->where(['pid' => $val['cate_id']])->order('sort')->select();
//                    if ($cate_son) {
//                        $val['cate_son'] = $cate_son;
//                    } else {
//                        $val['cate_son'] = [];
//                    }
//                }
//
//                unset($val);
//            }
        }

        $cateList = M('GoodsCate')->field('cate_id,title,pid')->where($where)->order('sort')->select();


        if (!empty($cateList)) {
            foreach ($cateList as &$val) {
                $cate_son = M('GoodsCate')->field('cate_id,title,pid')->where(['pid' => $val['cate_id']])->order('sort')->select();
                if ($cate_son) {
                    $val['cate_son'] = $cate_son;
                } else {
                    $val['cate_son'] = [];
                }
            }

            unset($val);
        }
        $this->success('获取成功', $cateList);
    }

    public function getRecmdKeyword() {
        $where['is_recmd'] = 1;
        $keywords = M('SearchKeywords')->field('key_id,keywords')->where($where)->order('search_num desc')->limit(0, 8)->select();
        $this->success('获取成功', $keywords);
    }

    public function getIndexCate() {
        $cateList = M('GoodsCate')->field('cate_id,title,icon')->where(['pid' => 0, 'is_index' => 1])->order('sort')->select();

        if (!empty($cateList)) {
            foreach ($cateList as &$val) {
                $val['icon'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['icon'];
            }

            unset($val);
        } else {
            $cateList = [];
        }

        $data = M('Configure')->where(array("key" => "lrgs"))->find();

        $value = [];
        if (!empty($data)) {
            $value = unserialize($data['value']);
        }

        if (!empty($value['icon'])) {
            $value['icon'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $value['icon'];
        }

        $value['url'] = 'http://' . $_SERVER['HTTP_HOST'] . U('Other/index');

        $cateList[] = array('icon' => $value['icon'], 'title' => '懒人故事', 'cate_id' => -10, 'url' => $value['url']);
        $this->success('获取成功', $cateList);
    }

    public function getIndexInfo() {

        $where['is_del'] = 0;
        $where['is_index'] = 1;

        $list = M('Information')
                ->field('info_id,title,view_num,create_time')
                ->where($where)
                ->order('sort')
                ->select();

        if (empty($list)) {
            $list = [];
        }

        $this->success('获取成功', $list);
    }

    public function getCenterList() {
        $centerList = M('Center')->field('center_id,center_name,center_icon,type')->order('sort')->select();

        if (!empty($centerList)) {
            foreach ($centerList as &$val) {
                $val['center_icon'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['center_icon'];
            }

            unset($val);
        } else {
            $centerList = [];
        }
        $this->success('获取成功', $centerList);
    }

    public function getKefurexian() {
        $data = M('Configure')->where(array("key" => "kefurexian"))->find();
        $value = [];
        if (!empty($data)) {
            $value = unserialize($data['value']);

            if (!empty($value['qcode1'])) {
                $value['qcode1'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $value['qcode1'];
            }

            if (!empty($value['qcode2'])) {
                $value['qcode2'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $value['qcode2'];
            }
        }

        $this->success('获取成功', $value);
    }

    public function getLrgsInfo() {
        $data = M('Configure')->where(array("key" => "lrgs"))->find();

        $value = [];
        if (!empty($data)) {
            $value = unserialize($data['value']);
        }

        if (!empty($value['icon'])) {
            $value['icon'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $value['icon'];
        }

        $value['url'] = 'http://' . $_SERVER['HTTP_HOST'] . U('Other/index');

        $this->success('获取成功', $value);
    }

    public function test() {
        sendjpush(['title' => '测试推送']);
    }
    
    public function check(){
        $data = M('Configure')->where(array("key" => "check"))->getField('desc');

        $this->success('',$data);
    }

}
